package com.rexolar.openapi.utlis;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.digest.HMac;
import com.alibaba.fastjson.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;

/**
 * @author zhusiyu
 * @description:  MD5加密
 * @date 2019-12-25
 **/
public class EncryptUtil {

    private static final String HMAC_MD5_ALGORITHM = "HmacMD5";

    public static String getToSign(Map<String, String> params, String secret) {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);
        for (String key : keys) {
            if (key!=null && !key.trim().isEmpty()) {
                String value = params.get(key);
                if (null != value) {
                    query.append(key.trim());
                    query.append(value.trim());
                }
            }
        }
        query.append(secret);
        return getSignByHmac(query.toString(), secret);
    }

    /**
     * 根据MD5算法获取加密字符串
     * */
    public static String getSignByHmac (String str, String secretKey) {
        try {
            HMac hMac = new HMac(HMAC_MD5_ALGORITHM, secretKey.getBytes(StandardCharsets.UTF_8));
            return encodeBase64(hMac.digest(str));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * MD5 加密
     */
    public static String getMd5Str(String str) {
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        return md5.digestHex(str);
    }


    public static String encodeBase64(byte[] bytes) {
        return new String(Base64.getEncoder().encode(bytes));
    }

    public static void main(String[] args) throws Exception {
        sign();
    }

    private static void sign() {
//        String params = "{\"clientId\":\"0c629dc884b04aef19c55fbd35b9cc9b\",\"method\":\"css.hello.cloud.user.logout\",\"sign\":\"a7b53fd8f30c536e6276910d6abe1385\",\"appKey\":\"yunkefu-jmp6TQeb\",\"timestamp\":\"1630393583\",\"token\":\"3afa8e4fb3494fe9afba3a91d9da3a77\"}";
        String params = "{\"method\":\"invokeTslService4oi\",\"appKey\":\"b10c700780f245a29861e7e90b602297-4U74qBCz\",\"timestamp\":\"1625040972\",\"data\":\"{\\\"productId\\\":\\\"65537\\\",\\\"iotId\\\":\\\"00CCF9BC020002000172\\\",\\\"tslServiceDTO\\\":{\\\"serviceName\\\":\\\"refresh\\\",\\\"serviceParams\\\":{\\\"reason\\\":0}}}\"}";
        JSONObject jsonObject1 =JSONObject.parseObject(params);

        String sign  = (String) jsonObject1.remove("sign");
        String secret = "488896609b5f4bae84c8b1e9bc92adfd";
        // 第二步：把所有参数名和参数值串在一起

        String[] keys = jsonObject1.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);
        for (String key : keys) {
            Object value = jsonObject1.get(key);
            if (null != key) {
                query.append(key.trim());
            }
            if (null != value) {
                query.append(URLUtil.decode(String.valueOf(value)));
//                query.append(value);
            }
        }
        System.out.println("StringToSign: " + query.append(secret));
        System.out.println("sign: " + getSignByHmac(query.toString(), secret));
        System.out.println("paramSign: " + sign);


//        query.append(secret);
//        return getMD5Str(query.toString());
////        jsonObject1.put("appKey", "helloworld");
////        System.out.println("param sign: "+jsonObject1.remove("sign"));
//
////        signTopRequest1(jsonObject1, "appSecret1");
//        System.out.println("signTopRequest  sign: " + signTopRequest(jsonObject1, "helloworld"));
//        System.out.println("getMD5Str:"+  v(query.toString()));
//        System.out.println("HmacMD5DigestAsHex:"+ HmacMD5DigestAsHex(params,"helloworld"));
//        System.out.println("md5DigestAsBase64:"+ md5DigestAsBase64(params));
//        System.out.println("encodeBase64:"+ encodeBase64(getMd5(params)));
//        System.out.println("getMd5Str:"+ getMd5Str(params));
//        System.out.println("encodeHex:"+  new String(encodeHex(getMd5(params))));
//        System.out.println("toHex:"+  toHex(getMd5(params)));
    }
}
